import {
  formatSeconds
} from '../../../utils/util.js'

let app = getApp()
Page({
  data: {
    spinShow: false,
    score: 0,
    paperId: null,
    examPaperAnswerId: null,
    form: {},
    timer: null,
    doTime: 0,
    userInfo: null,
    remainTime: 0,
    remainTimeStr: '',
    modalShow: false,
    result: 0,
    timeOutShow: false,
    address: "未打开地理位置授权！",
    latitude: null,
    longitude: null
  },
  onShow: function () {

  },
  onLoad: function (options) {
    let paperId = options.id
    let _this = this
    // _this.setData({
    //   paperId: options.id,
    // });

    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        _this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        wx.cloud.callFunction({
          config: {
            env: 'dabenben-jrvrn'
          },
          // 要调用的云函数名称
          name: 'getLocation',
          // 传递给云函数的参数
          data: {
            lat: latitude,
            lng: longitude
          },
          success: res => {
            console.log(res.result.result.address)
            _this.setData({
              address: res.result.result.address,
            });
          },
          fail: err => {
            console.log(err)
          },
        })
      },
      fail(){
        wx.showModal({
          title: '提示',
          content: '您拒绝位置信息，无法参与考试！请打开位置共享，方可参与考试！',
          success (res) {
            if (res.confirm) {
              wx.openSetting({
                success (res) {
                  console.log(res.authSetting)
                  wx.navigateTo({
                    url: '../../examPapers1/index',
                  })
                }
              })
            } else if (res.cancel) {
              wx.navigateTo({
                url: '../../examPapers1/index',
              })
            }
            }
        })

      }
    });
    wx.getNetworkType({
        success(res) {
          const networkType = res.networkType
          if (networkType != "wifi") {
            wx.showModal({
              title: '提示',
              content: '当前网络为' + networkType + ',建议使用WIFI网络参与考试！'
            })
          }
        }
      }),
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success() {
                console.log("获取授权位置信息成功！")
              }
            })
          }
        }
      });
    // app.formPost('/api/wx/student/user/current', null).then(res => {
    //   if (res.code == 1) {
    //     _this.setData({
    //       userInfo: res.response,
    //     });
    //   }
    // });
    wx.enableAlertBeforeUnload({
      message: '确认退出考试？退出考试将自动提交试卷！',
      success: res => {
        wx.vibrateShort({
          type: 'heavy'
        })
      },
      fail: err => {}
    });
    wx.onUserCaptureScreen(function (res) {
      wx.showModal({
        title: '提示',
        content: '严禁截屏，如有下次，自动提交试卷！'
      })
    });
    _this.setData({
        spinShow: true
      }),
      app.formPost('/api/wx/student/exampaper/select/' + paperId, null)
      .then(res => {
        _this.setData({
          spinShow: false,
          userInfo:app.globalData.userInfo,
          score: res.response.score
        });
        if (res.code === 1) {
          _this.setData({
            form: res.response,
            paperId: paperId,
            remainTime: res.response.suggestTime * 60
          });
          _this.timeReduce()
        }
      }).catch(e => {
        _this.setData({
          spinShow: false
        });
        app.message(e, 'error')
      })
  },
  timeReduce() {
    let _this = this
    let timer = setInterval(function () {
      let remainTime = _this.data.remainTime
      if (remainTime <= 0) {
        _this.timeOut()
      } else {
        _this.setData({
          remainTime: remainTime - 1,
          remainTimeStr: formatSeconds(remainTime),
          doTime: _this.data.doTime + 1
        });
      }
    }, 1000)
    _this.setData({
      timer: timer
    });
  },
  onUnload() {
    clearInterval(this.data.timer)
  },

  returnRecord() {
    // wx.reLaunch({
    //   url: '/pages/record/index',
    // });
    app.globalData.examPaperAnswerId = this.data.examPaperAnswerId,
      // app.globalData.userScore =  this.data.score,
      console.log("我要传输的ID是" + this.data.examPaperAnswerId),
      wx.navigateTo({
        url: '/packageF/exam/result/index?id=' + app.globalData.examPaperAnswerId,
      })
  },
  timeOut() {
    clearInterval(this.data.timer)
    this.setData({
      timeOutShow: true
    });
    wx.vibrateShort({
      type: 'heavy'
    })
  },
  formSubmit: function (e) {
    let _this = this
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    e.detail.value.id = this.data.paperId
    e.detail.value.doTime = this.data.doTime
    e.detail.value.address = this.data.address
    e.detail.value.latitude = this.data.latitude
    e.detail.value.longitude = this.data.longitude
    let title = this.data.form.name
    app.formPost('/api/wx/student/exampaper/answer/answerSubmit', e.detail.value)
      .then(res => {
        if (res.code === 1) {
          _this.setData({
            modalShow: true,
            result: res.response.score,
            examPaperAnswerId: res.response.examPaperAnswerId
          });
          app.globalData.userScore = res.response.score
          let fenshu = res.response.score;
          console.log(fenshu);
          let userName = _this.data.userInfo.realName;
          console.log(userName);
          let paperScore = (_this.data.score * 0.6).toFixed();
          console.log(paperScore);
          let address = _this.data.address
          console.log(address)
          wx.cloud.callFunction({
            name: 'getOpenId'
          }).then(res => {
            console.log(res);
            let openid = res.result.openid
            console.log("获取openid成功！", openid)
            wx.cloud.callFunction({
              config: {
                env: 'dabenben-jrvrn'
              },
              // 要调用的云函数名称
              name: 'sendNewMsg',
              // 传递给云函数的参数
              data: {
                openid: openid,
                // theme:"本次考试"+jige+",有问题联系陈鹏！",
                theme: address,
                number: fenshu,
                title: title,
                username: userName,
                bukao: "本次考试及格分：" + paperScore + "分"
              },
              success: res => {
                console.log(res)
              },
              fail: err => {
                console.log(err)
              },
            })
          })
          wx.vibrateShort({
            type: 'medium'
          })
        } else {
          app.message(res.response, 'error')
        }
        wx.hideLoading()
      }).catch(e => {
        wx.hideLoading()
        app.message(e, 'error')
      })
  }
})